﻿using System.Xml.Serialization;
using System.IO;

namespace GFC
{
    class FormatSaverAndLoader
    {
        private static FormatSaverAndLoader m_Instance = null;
        public static FormatSaverAndLoader Instance
        {
            get
            {
                if (m_Instance == null)
                    m_Instance = new FormatSaverAndLoader();
                return m_Instance;
            }
        }

        private FormatSaverAndLoader()
        {
        }

        public void Save(Stream writer, Format format)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Format));
            serializer.Serialize(writer, format);
        }

        public void Save(string path, Format format)
        {
            using (FileStream writer = new FileStream(path, FileMode.Create))
            {
                this.Save(writer, format);
            }
        }

        public Format Load(Stream reader)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Format));
            Format format = (Format)serializer.Deserialize(reader);

            //Fix parents references
            if(format != null && format.Frames != null)
            {
                foreach (Frame frame in format.Frames)
                {
                    if (frame != null)
                    {
                        frame.Format = format;
                        if (frame.Fields != null)
                        {
                            foreach (Field field in frame.Fields)
                            {
                                if (field != null)
                                    field.Frame = frame;
                            }
                        }
                    }
                }
            }

            return format;
        }

        public Format Load(string path)
        {
            using (FileStream reader = new FileStream(path, FileMode.Open))
            {
                return this.Load(reader);
            }
        }
    }
}
